package com.atguigu.guli.service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.oss.service.FileService;
import com.atguigu.guli.service.oss.utils.OssProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    OssProperties ossProperties;

    String schema;
    // Endpoint以杭州为例，其它Region请按实际情况填写。
    String endpoint;
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
    String accessKeyId;
    String accessKeySecret;
    String bucketName;

    @PostConstruct//jdk提供的 bean的构造器后立即执行的初始化方法
    public void init(){
        this.schema=ossProperties.getSchema();
        this.accessKeyId=ossProperties.getAccessKeyId();
        this.accessKeySecret=ossProperties.getAccessKeySecret();
        this.endpoint=ossProperties.getEndpoint();
        this.bucketName=ossProperties.getBucketName();
    }


    @Override
    public String uploadFile(MultipartFile file, String module) {
        try {
        OSS ossClient = new OSSClientBuilder().build(schema + endpoint, accessKeyId, accessKeySecret);
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();//文件名称
            //文件上传的优化
        //1、给文件设置唯一的文件名
        String fileName = UUID.randomUUID().toString().replace("-", "") +
                originalFilename.substring(originalFilename.lastIndexOf("."));

        String dateStr = new DateTime().toString("/yyyy/MM/dd/");

        ossClient.putObject(bucketName,
                //key：表示文件保存在桶内的 路径+文件名
                module + dateStr + fileName, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        //获取上传成功的文件地址
        return schema + bucketName + "." + endpoint + "/" + module + dateStr + fileName;
        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException(e.getMessage());
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR,e);
        }
    }

    @Override
    public void deleteFile(String path, String module) {
        String objectName = path.substring(path.lastIndexOf(module));
        OSS ossClient = new OSSClientBuilder().build(schema+endpoint,
                accessKeyId, accessKeySecret);

// 删除文件或目录。如果要删除目录，目录必须为空。
        ossClient.deleteObject(bucketName, objectName);

// 关闭OSSClient。
        ossClient.shutdown();
    }
}
